const upgradeToV3 = (db, callback) => {
  let pending = 2;
  const errors = [];

  function finish(err) {
    if (err) {
      errors.push(err);
    }
    if (--pending === 0) {
      callback(errors.length > 0 ? errors : null);
    }
  }

  const checkAndAddColumn = (table) => {
    db.all(`PRAGMA table_info(${table})`, (err, rows) => {
      if (err) {
        finish(err);
      } else {
        const hasCodeColumn = rows.some((row) => row.name === 'code');
        if (!hasCodeColumn) {
          db.run(`ALTER TABLE ${table} ADD COLUMN code INTEGER`, finish);
        } else {
          finish();
        }
      }
    });
  };

  checkAndAddColumn('uploads');
  checkAndAddColumn('downloads');
};

module.exports = upgradeToV3;
